 

package com.zdkj.subway.rca.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.subway.rca.entity.SwCkOthenTicketreturn;
import com.zdkj.subway.rca.entity.SwCkOthenTicketreturnLog;
import com.zdkj.subway.rca.service.SwCkOthenTicketreturnLogService;
import com.zdkj.subway.rca.service.SwCkOthenTicketreturnService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;


/**
 * 报表调账-其他运营商退换票导入日志表管理
 *
 * @author stw
 * @date 2020-12-31 19:38:11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swckothenticketreturnlog" )
@Api(value = "swckothenticketreturnlog", tags = "报表调账-其他运营商退换票导入日志表管理")
public class SwCkOthenTicketreturnLogController {

    private final SwCkOthenTicketreturnLogService swCkOthenTicketreturnLogService;

    @Autowired
    private final SwCkOthenTicketreturnService swCkOthenTicketreturnService;
    
    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwCkOthenTicketreturnLogPage(Page page, String lineCode, String reportType, String beginTime, String endTime) {
        SwCkOthenTicketreturnLog swCkOthenTicketreturnLog = new SwCkOthenTicketreturnLog();
//        if(StringUtils.isNotEmpty(beginTime)){
//            swCkOthenTicketreturnLog.setBeginTime(LocalDate.parse(beginTime, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//        }
//        if(StringUtils.isNotEmpty(endTime)){
//            swCkOthenTicketreturnLog.setEndTime(LocalDate.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//        }

        return R.ok(swCkOthenTicketreturnLogService.page(page, Wrappers.query(swCkOthenTicketreturnLog).lambda()
                .ge(StringUtils.isNotEmpty(beginTime), SwCkOthenTicketreturnLog::getBeginTime, beginTime)
                .le(StringUtils.isNotEmpty(endTime), SwCkOthenTicketreturnLog::getEndTime, endTime)
                .eq(SwCkOthenTicketreturnLog::getDelFlag,"0")
                .eq(StringUtils.isNotEmpty(lineCode), SwCkOthenTicketreturnLog::getLineCode, lineCode)
                .eq(StringUtils.isNotEmpty(reportType), SwCkOthenTicketreturnLog::getReportType, reportType)
                .groupBy(SwCkOthenTicketreturnLog::getBeginTime,SwCkOthenTicketreturnLog::getEndTime,
                        SwCkOthenTicketreturnLog::getReportType,SwCkOthenTicketreturnLog::getLineCode)
                .orderByDesc(SwCkOthenTicketreturnLog::getCreateTime)
        ));
    }

    /**
     * 正常情况退票导出模板
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "正常情况退票导出模板", notes = "正常情况退票导出模板")
    @GetMapping("/exportTamplateNormal")
    //@PreAuthorize("@pms.hasPermission('sw_ck_othen_yjzp_management_import')")
    public void exportTamplateNormal(HttpServletResponse response) {
        swCkOthenTicketreturnLogService.exportTamplateNormal(response);
    }
	 /**
     * 特殊情况退票导出模板
     * @param
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "特殊情况退票导出模板", notes = "特殊情况退票导出模板")
    @GetMapping("/exportTamplateSpecial")
    //@PreAuthorize("@pms.hasPermission('sw_ck_othen_yjzp_management_import')")
    public void exportTamplateSpecial(HttpServletResponse response) {
        swCkOthenTicketreturnLogService.exportTamplateSpecial(response);
    }

    @ApiOperation(value = "导入", notes = "导入")
    @SysLog("导入其他运营商退换票")
    @PostMapping(value = "/saveBatch", headers = "content-type=multipart/form-data")
    //@PreAuthorize("@pms.hasPermission('sw_ck_othen_yjzp_management_import')")
    public R saveBatch(@RequestParam(value = "file") MultipartFile file) throws Exception {
        return R.ok((Object) this.swCkOthenTicketreturnLogService.saveBatchWithExcel(file));
    }

    /**
     * 浏览
     * @return
     */
    @ApiOperation(value = "浏览，（id:浏览的那条数据的ID）", notes = "浏览，（id：浏览的那条数据的ID）")
    @GetMapping("/listPreview" )
    //@PreAuthorize("@pms.hasPermission('sw_ck_othen_yjzp_management_import')")
    public R listPreview(Long id,String reportType) throws Exception {
        if(id == null){
            return R.ok(CommonConstants.FAIL);
        }

        SwCkOthenTicketreturnLog logObj =  this.swCkOthenTicketreturnLogService.getById(id);
        SwCkOthenTicketreturn swCkOthenTicketreturn = new SwCkOthenTicketreturn();
        //swCkOthenTicketreturn.setLogId(logObj.getUuid());
        //List<SwCkOthenTicketreturn> list = swCkOthenTicketreturnService.list(Wrappers.query(swCkOthenTicketreturn));

       
		String startDate =  logObj.getBeginTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));		
		String endDate =    logObj.getEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

		QueryWrapper<SwCkOthenTicketreturn> queryWrapper = new QueryWrapper<SwCkOthenTicketreturn>();
        queryWrapper.between("statistics_date", startDate, endDate);
        queryWrapper.eq("LINE_CODE",logObj.getLineCode());
        queryWrapper.eq("REPORT_TYPE",logObj.getReportType());

        //swCkOthenTicketRevenueManagement.setLogId(logObj.getUuid());
		List<SwCkOthenTicketreturn> list = swCkOthenTicketreturnService.list(queryWrapper);
        
		 if(list != null && !list.isEmpty()){
                 List<Map<String,String>> projectItemMap = swCkOthenTicketreturnService.selectPaymentMethodItemMap();
				 List<Map<String,String>> serviceOrgItemMap = swCkOthenTicketreturnService.selectServiceOrgItemMap();
                 for(SwCkOthenTicketreturn obj : list){
                     obj.setSalePaymentmethod(getProjectItemName(projectItemMap,obj.getSalePaymentmethod()));
                     obj.setReturnPaymentmethod(getProjectItemName(projectItemMap,obj.getReturnPaymentmethod()));
					 obj.setServiceOrg(getServiceOrgItemName(serviceOrgItemMap,obj.getServiceOrg()));
                 }
        }

        return R.ok(list);

    }
    /**
     * 获取项目名称
     * @param projectItemMap
     * @param projectItem
     * @return
     */
    private String getProjectItemName (List<Map<String,String>> projectItemMap,String projectItem) {
        for (Map<String,String> map : projectItemMap){
            if(projectItem.equals(map.get("value"))){
                return map.get("label");
            }
        }
        return "/";
    }
    /**
     * 获取运营商名称
     * @param projectItemMap
     * @param projectItem
     * @return
     */
    private String getServiceOrgItemName (List<Map<String,String>> projectItemMap,String projectItem) {
        for (Map<String,String> map : projectItemMap){
            if(projectItem.equals(map.get("serviceId"))){
                return map.get("serviceName");
            }
        }
        return "/";
    }
}
